<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SessionsController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest', [
            'only' => ['create']
        ]);
    }

    public function create()
    {
        return view('sessions.create');
    }

    public function store(Request $request)
    {
        $this->validate($request,[
           'email' => 'required|email|max:255',
           'password' => 'required'
        ]);
        $requests = [
          'email' => $request->email,
          'password' => $request->password
        ];
        if (Auth::attempt($requests,$request->has('remember'))){
            if (Auth::user()->activated){
                session()->flash('success','欢迎回家');
                $fallback = route('users.show',Auth::user());
                return redirect()->intended($fallback);
            }else{
                Auth::logout();
                session()->flash('warning','你的账号未激活，请检查邮箱中的注册邮件进行激活。');
                return redirect()->route('home');
            }

        }else{
            session()->flash('danger','账号或者密码错误');
            return redirect()->back()->withInput();
        }

    }


    public function destroy()
    {
        Auth::logout();
        session()->flash('success','下次再见');
        return redirect()->route('login');
    }
}
